// pages/Bargain/Bargain.js

const app = getApp();
const net = require('../../utils/request.js');
var WxParse = require('../../components/wxParse/wxParse.js');
var utilsTest = require("../../utils/transhform.js"); //日期转换


var is_tapLogin = 1;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: '昵称',
    avatarUrl: '../../image/touxiang@2x.png', //
    codeImage: app.globalData.service + "bargain/index/verify?openid=" + app.globalData.openid,
    sendBtnClass: 'sendBtn1', //获取短信验证码的class sendBtn2
    btnTitle: '获取验证码', //获取短信验证码按钮的title
    phonenumber: '', //手机号码
    checkCode: '', //短信验证码
    titlDetailList: '暂无好友帮忙',
    list: [],
    isshowNoFriend: 0, //没有人帮忙砍价提示
    ishidePop: 0, //弹窗类型,0 弹窗消失 ,1登录弹窗,2 领取代金券
    percent: 0, //进度条百分比,

    showType: 1, //1未发起砍价状态, 2已发起砍价,3,已领取优惠券,4帮他砍价,5我也要发起砍价 6,活动结束 7已经砍满
    msgCode: '', //短信验证码
    jianMoney: 50, //满减券金额
    manMoney: 8000, //满减券起投金额
    minMoney: 3000, //满减券砍至最低金额;
    activeState: 1, //活动状态,1 开启 0 活动关闭

    starTime: '2019.01.02', //活动开启时间
    endTime: '2019.01.03', //活动关闭时间,

    rule: '这里是规则,规则规则阿斯顿发送到发sad凝聚力你心脏病', //活动规则,
    yikan: 0, //一看家左边left;
    rightFloatView: 'mainbody-kanjiaright', //mainbody-kanjiaright 未满右 mainbody-kanjia满之后 左 fuloatViewNotMan 未满左
    floatTitle: '7200元(已砍800元)', // {{manMoney-(manMoney-minMoney)/100*percent}}元(已砍{{(manMoney-minMoney)/100*percent}}元)
    loadinSure: 'woyilingqu', //redBtn,

    form_id: '', //临时需要的登录用到的from_id
    help_id: '0', //被帮助者的openid;

    manjianjine: 0, //当前满减的满,  例如manjianjine等于3000  就是已经砍了7000

    is_new: 0, //是不是新人;  1 是新人. 0 不是新人
    is_bargain: 0, //是否发起过砍价,
    is_Checked: 0, //是否帮助过
    is_get: 0, //是否已领取.
    is_have: 0, //当前有没有券.等同于是都发起过砍价.
    bangtakanjia: '今天好友帮砍金额已达上限',
    is_status: '0', // 帮助过这个人1 已帮助过 2已领取  3 已满

    loadType: 1, //登录的几种情况 1正常登录 2砍价登录 3,发起砍价登录,
    tempList:[],///为了做收缩板块,特意写了一个临时的;
    endActivey:1,//活动是否开启
    today:1,//砍价 信息是不是今天的 如果没有发起砍价 后台不会返回券的信息,会返回昨天卷的信息;
    
    tem_userID:'0',//临时存放从app过来之后的user_id
    tem_token:'0',//临时存放从app过来之后的user_token;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //自定义控件
    this.dialog = this.selectComponent("#dialog");
    var that = this;
    //(1)从app 进来的传的参数;
    that.existUserID(options);
    //(2)长期没进来之后 再次进入
    that.checkIfHaveLoadMesssage();//获取信息
    //检查有没有 help_id
    that.checkHelpId(options);
    //(3) 平常进入 (检索登录状态以及授权信息;)
    //检查是否有登陆过的记录;
    that.refrshImage(); //刷新图片
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var that = this;
   
    // 请求全局配置
    that.eventGlobel();
    
    // 去哪openid;
    that.getOpenid();
    
    that.refrshImage();

    if (that.data.endActivey == 0) {
      that.setData({
        showType: 6,
      });
      return;
    }
    //重新获取页面全部信息;
    that.chongzhiyemian();
    setTimeout(function () {
      that.chongzhiyemian();
    }, 1000);
    //刷新图片
   //获取当前页面按钮状态
   that.jianchadangqianyemian();
   //弹窗
   that.BargainDialog = that.selectComponent("#BargainDialog");
    // that.BargainDialog.showDialog();
    // that.BargainDialog.showType(4,500,0,0);
    
  },

  // 已经存在 user_id;从app进来的;
  existUserID: function (options) {
    var that = this;
    if (options.user_id !== undefined && options.user_token !== undefined) {
      if (options.user_id !== '' && options !== '') {
        var userinfo = {
          'user_id': options.user_id,
          'user_token': options.user_token
        };
        wx.getUserInfo({
          success: function (ress) {
            setTimeout(function () {
              that.setData({
                nickName: ress.userInfo.nickName,
                avatarUrl: ress.userInfo.avatarUrl,
              });
            }, 1000);

            wx.setStorage({
              key: 'userInfo',
              data: userinfo,
            })
            app.globalData.user_id = options.user_id;
            app.globalData.user_token = options.user_token;
          },
          fail: function () {
            wx.setStorage({
              key: 'noAuthorization',
              data: userinfo,
            });
            that.setData({
              tem_userID: options.user_id,
              tem_token: options.user_token
            });
          },
        })
      }
    }
  },
  //检查helpId
  checkHelpId: function (options) {
    var that = this;
    if (options.help_id !== undefined && options.help_id !== 0) {
      if (that.checkIfHaveLoadMesssage()) {//如果已登录
        if (options.help_id == app.globalData.user_id) {
          //如果和自己的user_id一样;
          that.setData({
            help_id: '0',
          });
        } else {
          //如果和自己的user_id不一样;
          that.setData({
            help_id: options.help_id,
            loadType: 2,
          });
        }
      } else {
        //如果没有登录;
        that.setData({
          help_id: options.help_id,
          loadType: 2,
        });
      }
    }
  },
  // =================================跳转至新人界面 
  turnToweafear: function(sta, zhijiangm, kanjiam, hongbaom) {
    /*
    state = 1,2,3,4; //  1 新人专享页面   2,成功帮砍 3可惜了已领取  4 好友砍价已达上限
    zhijiang:5000 
    kanjia:500  // 砍价成功
    hognbao:50
     sta = 4;
    zhijiangm = 7000;
    kanjiam = 300;
    hongbaom = 60;
     nickName: '昵称',
    avatarUrl:
    */
   console.log('掉员工新人页面');
   var that = this;
    wx.reLaunch({
      url: '../welfare/welfare?state=' + sta + '&zhijiang=' + zhijiangm + '&kanjia=' + kanjiam + '&hongbao=' + hongbaom + '&nickName=' + that.data.nickName +'&avatarUrl='+that.data.avatarUrl,
    });
  },
  //============================= 重置页面所有信息=
  chongzhiyemian: function() {
    var that = this;
    //获取个人信息;以及帮助加息的人和是否发起过,是否有人帮助过.
    that.huoquxinxi();
    if (that.data.endActivey == 0) {
      that.setData({
        showType:6,
      });
      return;
    }
    
    // 检测是否 有好友帮忙助力
    that.isshowNoFriendAction();
    //进度条
    that.progressFun();
    //获取当前页面按钮状态
    that.jianchadangqianyemian();
  },
  // ===========================检查当前页面状态=
  jianchadangqianyemian: function () {
    var that = this;
    if (that.data.endActivey == 0) {
      that.setData({
        showType: 6,
      });
      return;
    }
    wx.setStorage({
      key: 'is_new',
      data: 0,
    })
    if (that.data.manjianjine == that.data.minMoney && that.data.list.length == 0) {
      that.setData({
        is_new: 1,
      });
      wx.setStorage({
        key: 'is_new',
        data: 1,
      })
    }
    if (that.data.is_new == 1) {
      that.setData({
        titlDetailList: "新人专享,无须砍价,直降¥" + (that.data.manMoney - that.data.minMoney)
      });
    }
    //是否发起过砍价
    if (that.data.is_bargain == 1) {

      that.setData({
        showType: 2, //已发起砍价
      });
      // 是否已经砍满
      if (that.data.manjianjine == that.data.minMoney) {
        that.setData({
          showType: 7, //已经砍满
        });
      }
      //是否已领取;
      if (that.data.is_get == 1) {
        that.setData({
          showType: 3,
        });
      }
    } else {
      that.setData({
        showType: 1, //未发起砍价
      });
    }

    //是否是别人让砍价的
    if (that.data.help_id != 0) { //帮助别人
      //今天是否帮助过
      var status = '';
      if (that.data.is_status == 1) {
        status = '我已帮TA砍价';
      } else if (that.data.is_status == 2) {
        status = '今天老铁已领取代金券';
      } else if (that.data.is_status == 3) {
        status = '今天累计好友帮砍金额已达上限';
      }
      //4帮他砍价, 5我也要发起砍价 6, 活动结束
      that.setData({
        showType: 4,
        bangtakanjia: status,
      });
      var myDate = new Date();
      var date = myDate.toLocaleDateString() + app.globalData.user_id;
      var ifhave = wx.getStorageSync('ifStartHelp');
      //是否点击过帮他砍价按钮;
      // 是否 帮助过别人
      if (date ==  ifhave && that.data.is_status != 0) {
        that.setData({
          showType: 5,
        });
      }
    }
  },
  //领取砍满代金券 
  lingqukanmandaijinquan: function() {
    var that = this;
    //领取代金券
    that.renglingqu();
  },
  //=================================帮Ta砍价
  bangtakanjia: function() {
    var that = this;
    wx.getUserInfo({
      success: function(ress) {

        if (app.globalData.user_id == undefined || app.globalData.user_id == 0 || app.globalData.user_id == '') {
          that.getopenid(); //获取openid;
          that.setData({
            ishidePop: 1,
            loadType: 2, //登录的几种情况 1正常登录 2砍价登录 3,发起砍价登录,
          });
          return;
        }
        net.requestHttp("bargain/index/help", {
          user_id: app.globalData.user_id,
          user_token: app.globalData.user_token,
          help_id: that.data.help_id,
        }, function(res) {

          console.log('帮他砍价返回数据');
          console.log(res);
          var myDate = new Date();
          //是否点击过帮他砍价按钮;
          wx.setStorage({
            key: 'ifStartHelp',
            data: '' + myDate.toLocaleDateString()+app.globalData.user_id,
          })

         
          if (res.data.state == 1) {
            console.log('砍价成功');

            //各种砍价成功的弹窗;
            if (that.data.is_new == 0) {
              console.log('不是新人');
              //如果不是新人,正常加息
              var status = '';
                console.log('======================我已帮他砍价==================');
                status = '我已帮TA砍价';
                that.BargainDialog.showDialog();
                that.BargainDialog.showType(1, res.data.data, 0, 0);
                console.log('=======================弹窗成功==================')
              that.setData({
                showType: 5,
                bangtakanjia: status, //页面出现不可点击按钮
              });
              console.log('成功======================页面状态发生改变');
            }else{

              //如果是新人.直接进入加息已满状态
              console.log('跳转新人页面 --- 如何跳转');
              that.turnToweafear(2, 0, res.data.data, that.data.jianMoney);
              // 直接领取代金券;
              // that.renglingqu();
            }
          } else {
            console.log('砍价失败');
            if (that.data.is_new == 1) {
              console.log('新人' + res.data.data.status );
              if (res.data.data.status == 1) {
                console.log('1状态');
                //turnToweafear:function(sta,zhijiangm,kanjiam,hongbaom)
                that.turnToweafear(2, 0, res.data.data, that.data.jianMoney);
              } else if (res.data.data.status == 2) {
                that.turnToweafear(3, 0, 0, that.data.jianMoney);
              } else if (res.data.data.status == 3) {
                that.turnToweafear(4, 0, 0, that.data.jianMoney);
              } else if (res.data.data.status == 0) {
                console.log('1状态');
                that.turnToweafear(5, 0, 0, that.data.jianMoney);
              }
              console.log('仍领取');
              // that.renglingqu();
            } else {
              console.log('不是新人' + res.data.data.status);
              //如果不是新人,正常加息
              var status = '';
              if (res.data.data.status == 1) {
                status = '我已帮TA砍价';
                that.BargainDialog.showDialog();
                that.BargainDialog.showType(1, res.data.data, 0, 0);
              } else if (res.data.data.status == 2) {
                status = '今天老铁已领取代金券';
                that.BargainDialog.showDialog();
                that.BargainDialog.showType(4, 500, 0, 0);
              } else if (res.data.data.status == 3) {
                status = '今天累计好友帮砍金额已达上限';
                that.BargainDialog.showDialog();
                that.BargainDialog.showType(3, 500, 0, 0);
              }
              that.setData({
                showType: 5,
                bangtakanjia: status, //页面出现不可点击按钮
              });
            }
          }
         
          that.chongzhiyemian();
        });
      },
    })

  },
  // ===========================仍领取代金券
  renglingqu: function() {
    var that = this;
    //重新获取一下信息

    that.huoquxinxi();
    setTimeout(function(){
      net.requestHttp("bargain/index/getPrize", {
        user_id: app.globalData.user_id,
        user_token: app.globalData.user_token
      }, function (res) {
        if (res.data.state == 1) {
          that.hidePop();
          if (that.data.is_new == 0) {
            //新人不提示
            that.BargainDialog.showDialog();
            that.BargainDialog.showType(2, 500, that.data.manjianjine, that.data.jianMoney);
          }
          //去掉help_id
          that.setData({
            help_id: '0',
          });
          that.chongzhiyemian();
        }
      });
    },500);
    
  },
  //  =================================领取当前代金券
  lingqudaijinquan: function() {
    var that = this;
    that.setData({
      ishidePop: 2, //领取代金券弹窗;
    });
  },
  //===================================进度条 动画完成时间;
  progressFun: function(res) {
    var that = this;

    if (that.data.is_bargain == 0) {
      that.setData({
        manjianjine: that.data.manMoney,
      });
    }

    var a = (that.data.manMoney - that.data.manjianjine) / (that.data.manMoney - that.data.minMoney) * 100;
    that.setData({
      percent: a,
      yikan: a * 6
    });
    // 检查进度条是否满了
    that.getpeocessValue();
  },
  // =====================================我也要发起砍价
  woyeyaofaqikanjia: function() {
    var that = this;
    that.setData({
      showType: 2,
      help_id: 0, //我也要发起砍价的时候,肯定不存在帮助别人的信息了,
    });

    wx.getUserInfo({
      success: function(ress) {
        that.setData({
          nickName: ress.userInfo.nickName,
          avatarUrl: ress.userInfo.avatarUrl,
        });
        that.faqikanjia();
      },
      fail: function() {

      },
    })

  },
  // ====================================发起砍价
  faqikanjia: function() {
    //判断是否已授权;
    var that = this;
    //发起砍价就不是在帮别人了
    if (that.data.help_id != 0) {
      that.setData({
        help_id: 0,
      });
    }

    wx.getUserInfo({
      success: function(ress) {
        that.getopenid();
        that.setData({
          nickName: ress.userInfo.nickName,
          avatarUrl: ress.userInfo.avatarUrl,
        });
        if(that.data.tem_userID != 0){
          //如果是从app进来的.
         var userinfo = wx.getStorageSync('noAuthorization');
          wx.setStorage({
            key: 'userInfo',
            data: userinfo,
          })
          app.globalData.user_id = that.data.tem_userID;
          app.globalData.user_token = that.data.tem_token;
          setTimeout(function(){
            //点击发起砍价(2期会改成这样.)
            // that.faqikanjiaAction();
            that.setData({
              ishidePop: 1, //1 登录弹窗;
              loadType: 1, //登录的几种情况 1正常登录 2砍价登录 3,发起砍价登录,
            });
          },1000);
          return;
        }
        
        if (that.checkIfHaveLoadMesssage()) {
          that.faqikanjiaAction();
        } else {
          that.getopenid();
          that.setData({
            ishidePop: 1, //1 登录弹窗;
            loadType: 1, //登录的几种情况 1正常登录 2砍价登录 3,发起砍价登录,
          });
        }
      },
      fail: function() {

      },
    });
  },
  //================================发起砍价接口
  faqikanjiaAction: function(e) {
    var that = this;
    net.requestHttp("bargain/index/startBargain", {
        user_id: app.globalData.user_id,
        user_token: app.globalData.user_token
      },
      function(res) {
        //  {"data":"","msg":"今天不能发起砍价了！","state":"0"}
        //  if(res.data.state==1){
        that.setData({
          showType: 2,
        });
        //请求页面所有信息;
        that.chongzhiyemian();
        //  }

      });
  },
  getpeocessValue: function() {
    var that = this;
    // var nowMoney = that.data.manMoney - (that.data.manMoney - that.data.minMoney) / 100 * that.data.percent;
    var nowMoney = that.data.manjianjine;
    var haveKan = that.data.manMoney - nowMoney;
    var zhijiang = that.data.manMoney - that.data.minMoney
    if (that.data.percent > 60 && that.data.percent < 100) {
      // manMoney-(manMoney-minMoney)/100*percent}}元(已砍{{(manMoney-minMoney)

      that.setData({
        rightFloatView: 'fuloatViewNotMan',
        yikan: that.data.yikan - 200,
        floatTitle: nowMoney + '元(已砍' + haveKan + '元)'
      });
    }
    if (that.data.percent <= 60) {
      that.setData({
        rightFloatView: 'mainbody-kanjiaright',
        yikan: that.data.yikan,
        floatTitle: nowMoney + '元(已砍' + haveKan + '元)'
      });
    }
    if (that.data.percent >= 100) {
      that.setData({
        rightFloatView: 'mainbody-kanjia',
        yikan: that.data.yikan - 130,
        floatTitle: '直降' + zhijiang + '元',
      });
      if(that.data.is_new==0){
        that.setData({
          floatTitle: '已砍' + zhijiang + '元',
        });
      }
    }
  },
  // =============================全局配置网络请求
  eventGlobel: function() {
    var that = this;
    net.requestHttp("bargain/index/event", {}, function(res) {
      if (res.data.data) {
        var article = res.data.data.rule;
        WxParse.wxParse('article', 'html', article, that, 5);
        that.setData({
          jianMoney: res.data.data.jian,
          manMoney: res.data.data.man,
          minMoney: res.data.data.min,
          activeState: res.data.state,
          starTime: utilsTest.formatDatedddd(parseInt(res.data.data.starttime)),
          endTime: utilsTest.formatDatedddd(parseInt(res.data.data.endtime)),
        });
        if(res.data.state==0){
          that.setData({
            endActivey:0,//活动关闭
          });
        }else{
          that.setData({
            endActivey: 1,
          });
        }
      } else {
        wx.showToast({
          title: '网络异常',
        });
      }
    });
  },
  //===============================获取信息,
  huoquxinxi: function() {
    var that = this;
    var checkid = '';

    if(app.globalData.user_id ==0 && that.data.help_id==0){
      return;
    }

    if (that.data.help_id != 0) {
      checkid = that.data.help_id;
    } else {
      checkid = app.globalData.user_id;
    }
    if (app.globalData.user_id == 0 && checkid == 0) {
      return;
    }

    net.requestHttp("bargain/index/getBargainInfo", {
      user_id: app.globalData.user_id,
      check_id: checkid,
    }, function(res) {
      console.log('---------------------------------------------')
      console.log(res);
      if (res.data.msg =='用户不存在'){
        that.setData({
          ishidePop: 1,
          loadType: 1, //登录的几种情况 1正常登录 2砍价登录 3,发起砍价登录,
        });
        return;
      }

      if (res.data.state == 1) {
        var tem =new Array();
        that.setData({
          tempList: res.data.data.help,
        });
        if (res.data.data.help.length>5){
          for(var a=0;a<5;a++){
            tem.push(res.data.data.help[a]);
          }
        }else{
          tem=res.data.data.help;
        }

        that.setData({
          manjianjine: res.data.data.now,
          is_bargain: res.data.data.is_bargain,
          is_Checked: res.data.data.checked,
          list: tem,
          is_get: res.data.data.get, //是否领取过
          is_have: res.data.data.is_have,
          is_status: res.data.data.status, //帮助过这个人1 已帮助过 2已领取  3 已满
          today: res.data.data.today,
        });
        //如果提示的邀请已过期或者已失效
        if (res.data.msg == '邀请已失效' || res.data.msg == '邀请已过期'){
          that.setData({
            manjianjine:that.data.manMoney,
            list: [],
          });

          /**
           *  is_new: 0, //是不是新人;  1 是新人. 0 不是新人
    is_bargain: 0, //是否发起过砍价,
    is_Checked: 0, //是否帮助过
    is_get: 0, //是否已领取.
    is_have: 0, //当前有没有券.等同于是都发起过砍价.
    bangtakanjia: '今天好友帮砍金额已达上限',
    is_status: '0', // 帮助过这个人1 已帮助过 2已领取  3 已满
           */
          //  istoday: res.data.data.today,//
        }
         //返回的不是今天的消息,并且不是自己主动进入
        if(res.data.data.today==0 && that.data.help_id==0){//如果返回的信息不是今天的,那么进度条和好友列表清空
          that.setData({
            manjianjine: that.data.manMoney,
            list: [],
            is_bargain:0,
          });
        }
       
         //返回的不是今天的消息,但是是从别人分享进入
        if (res.data.data.today == 0 && that.data.help_id == 0){
          that.setData({
            manjianjine: that.data.manMoney,
            list: [],
            is_bargain: 0,
            is_Checked: 0,
          });
        }
       
        if (that.data.help_id != 0) {
          that.setData({
            nickName: res.data.data.nickname,
            avatarUrl: res.data.data.headimgurl,
          });
        } else {
          wx.getUserInfo({
            success: function(ress) {
              if (that.data.help_id == 0) {
                that.setData({
                  nickName: ress.userInfo.nickName,
                  avatarUrl: ress.userInfo.avatarUrl,
                });
              }
            }
          });
        }
        that.progressFun();
        that.isshowNoFriendAction();
        //获取当前页面按钮状态
        that.jianchadangqianyemian();
      } else {

      }
    });
  },
  shousuolist:function(){
    var that = this;
    if(that.data.tempList.length==that.data.list.length){
      var tem = new Array();
      if (that.data.tempList.length > 5) {
        for (var a = 0; a < 5; a++) {
          tem.push(that.data.tempList[a]);
        }
      }else{
        tem = that.data.tempList;
      }
      that.setData({
        list: tem,
      })
    }else{
      that.setData({
        list:that.data.tempList,
      })
    }
  },
  //获取openid
  getOpenid: function() {
    var that = this;

    var openid = wx.getStorageInfoSync('openid');
    wx.login({
      success: function(res) {
        var code = res.code;
        //授权操作，获取openid 
        net.requestHttp('bargain/index/getopenid', {
            code: code
          },
          function(res) {
            if (res.data.state == 1) {
              wx.setStorage({
                  key: "openid",
                  data: res.data.data.openid
                }),
                wx.getUserInfo({
                  success: function(ress) {
                    console.log(ress);
                    if (that.data.help_id == 0) {
                      that.setData({
                        nickName: ress.userInfo.nickName,
                        avatarUrl: ress.userInfo.avatarUrl,
                      });
                    }
                  }
                });
              
              app.globalData.openid = res.data.data.openid;
              app.globalData.session_key = res.data.data.session_key;
              that.refrshImage();
            } else {
              //登录失败
              if(openid !== undefined || openid !== '' || openid !== '0'){
                app.globalData.openid = openid;
              }
            }
          }
        )
      },
      file: function() {
        console.log("shibai");
      },
    });
  },
  //检查是否有登录信息; check
  checkIfHaveLoadMesssage: function() {

    if (app.globalData.user_id == undefined || app.globalData.user_id == 0 || app.globalData.user_token == undefined || app.globalData.user_token.length < 4) {
      var userinfo = wx.getStorageSync('userInfo');
      if (userinfo && userinfo !== undefined && userinfo.user_id !== undefined && userinfo.user_token !== undefined) {
        //获取登录信息
        app.globalData.user_id = userinfo.user_id;
        app.globalData.user_token = userinfo.user_token;
        return true;
      }
      return false;
    } else {
      return true;
    }
  },
  // ================================是否有人帮忙砍价
  isshowNoFriendAction: function() {
    var that = this;
    var list = that.data.list;
    console.log(list.length)
    if (list.length == 0) {
      that.setData({
        isshowNoFriend: 1,
      });
    } else {
      that.setData({
        isshowNoFriend: 0,
      });
    }
  },
  // 弹窗引用
  showDialog() {
    this.dialog.showDialog();
  },
  //隐藏弹窗
  hidePop: function() {
    var that = this;
    that.setData({
      ishidePop: 0,
    });
  },
  //取消事件
  _cancelEvent() {
    console.log('你点击了取消');
    this.dialog.hideDialog();
  },
  //确认事件
  _confirmEvent() {
    console.log('你点击了确定');
    this.dialog.hideDialog();
  },
  // ============================================登录==========================
  //获取短信验证码
  getCode: function(e) {
    var that = this;
    var openid = wx.getStorageSync("openid");
    if (that.data.sendBtnClass == 'sendBtn2') {
      return;
    }
    //图形验证码
    if (that.data.checkCode.length < 4) {
      wx.showToast({
        title: '请输入正确的验证码',
        icon: 'none',
      })
      return;
    }
    // 手机号
    if (that.data.phonenumber.length < 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      })
      return;
    }
    wx.getUserInfo({
      success: function(ress) {
        if (openid) {
          net.requestHttp('bargain/index/getmobile', {
            mobile: that.data.phonenumber,
            imgcode: that.data.checkCode,
            openid: openid
          }, function(res) {
            if (res.data.state == 1) {
              wx.showToast({
                title: '发送验证码成功',
              })
              // 'sendBtn1',//获取短信验证码的class sendBtn2
              var currentTime = 60;
              var interval = setInterval(function() {
                that.setData({
                  btnTitle: '倒计时' + (currentTime - 1) + '秒',
                  sendBtnClass: 'sendBtn2',
                });
                currentTime--;
                if (currentTime <= 0) {
                  clearInterval(interval);
                  that.refrshImage();
                  that.setData({
                    btnTitle: '重新获取',
                    sendBtnClass: 'sendBtn1',
                  })
                }
              }, 1000);
            } else {
              that.refrshImage();
            }
          })
        } else {
          //请求一下 openid ,再掉用
          that.getopenid();
        }
      },
      file: function() {
        console.log('失败');
      }
    })
  },
  getopenid: function() {
    var that = this;
    wx.login({
      success(res) {
        if (res.code) {
          var code = res.code;
          net.requestHttp('bargain/index/getopenid', {
            code: code
          }, function(res) {
            console.log(res);
            if (res.data.state == 1) {
              wx.setStorage({
                  key: "openid",
                  data: res.data.data.openid
                }),
                that.setData({
                  openid: res.data.data.openid,
                });
              wx.getUserInfo({
                success: function(ress) {
                  if (that.data.help_id == 0) {
                    that.setData({
                      nickName: ress.userInfo.nickName,
                      avatarUrl: ress.userInfo.avatarUrl,
                    });
                  }
                }
              });
              app.globalData.openid = res.data.data.openid;
              app.globalData.session_key = res.data.data.session_key;
              that.refrshImage();
            } else {
              //登录失败
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  loginAction: function(res) {
    
    var that = this;
    if (that.data.phonenumber.length < 11) {
      wx.showToast({
        title: '请输入正确手机号码',
        icon: 'none'
      })
      return;
    }
    if (that.data.phonenumber.length == 0) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      });
      return;
    }
    if(is_tapLogin==1){
      is_tapLogin = 0;//标识是不是正在请求还没返回;
      wx.getUserInfo({
        success: function (ress) {
          if (that.data.help_id == 0) {
            that.setData({
              nickName: ress.userInfo.nickName,
              avatarUrl: ress.userInfo.avatarUrl,
            });
          }
          var user_id = '';
          if (that.data.help_id != 0) {
            user_id = that.data.help_id;
          }
          //授权操作，获取openid
          net.requestHttp('bargain/index/login', {
            mobile: that.data.phonenumber,
            openid: app.globalData.openid,
            smscode: that.data.msgCode,
            form_id: that.data.form_id,
            headimgurl: ress.userInfo.avatarUrl,
            nickname: ress.userInfo.nickName,
            user_id: user_id,
            channel: '2',
          },
            function (res) {
              is_tapLogin  = 1;
              if (res.data.state == 1) {
                app.globalData.userInfo = res.data.data;
                app.globalData.user_id = res.data.data.user_id;
                app.globalData.user_token = res.data.data.user_token;
                var userinfo = {
                  'user_id': res.data.data.user_id,
                  'user_token': res.data.data.user_token
                };
                wx.setStorage({
                  key: 'userInfo',
                  data: userinfo,
                })

                that.setData({
                  ishidePop: 0, //不弹窗;
                  is_new: res.data.data.is_new, //是不是新人.
                });
                wx.setStorage({
                  key: 'is_new',
                  data: res.data.data.is_new,
                })

                //登录的几种情况 1正常登录 2砍价登录 ,3发起砍价登录,
                console.log('--------' + that.data.loadType + '0000000000000000' + '是不是新人' + that.data.is_new);
                if (that.data.is_new == 1) {
                  if (that.data.loadType == 1) {
                    //turnToweafear:function(sta,zhijiangm,kanjiam,hongbaom)
                    that.turnToweafear(1, that.data.manMoney - that.data.minMoney, 0, that.data.jianMoney); //1 平常登录新
                  } else if (that.data.loadType == 2) {
                    if (that.data.today == 1) {
                      //如果信息是今天的就帮他砍价,要不然会老是提示 已失效
                      that.bangtakanjia(); //帮他砍价
                    }
                  } else if (that.data.loadType == 3) {
                    that.faqikanjia(); //发起砍价登录
                  }
                  // that.renglingqu(); //直接领取代金券
                } else {
                  if (that.data.loadType == 2) {
                    if (that.data.today == 1) {
                      //如果信息是今天的就帮他砍价,要不然会老是提示 已失效
                      that.bangtakanjia(); //帮他砍价
                    }
                  } else if (that.data.loadType == 3) {
                    that.faqikanjia(); //发起砍价登录
                  }
                }
                that.chongzhiyemian(); //重新刷新页面所有信息
              }
            }
          )
        }
      });
    }
    

  },
  //输入图片验证码
  inputImageCode: function(e) {
    var that = this
    that.setData({
      checkCode: e.detail.value
    })
    that.checkIfHaveValue();
  },
  //手机号
  inputPhoneNum: function(e) {
    var that = this
    that.setData({
      phonenumber: e.detail.value
    })
    that.checkIfHaveValue();
  },
  //短信验证码
  inputPhoneCode: function(e) {
    var that = this
    that.setData({
      msgCode: e.detail.value
    });
    that.checkIfHaveValue();
  },
  //核对是否填写信息
  checkIfHaveValue: function() {
    var that = this;
    if (that.data.phonenumber.length == 11 && that.data.msgCode.length == 6 && that.data.checkCode.length == 4) {
      that.setData({
        loadinSure: 'redBtn', //redBtn
      });
    } else {
      that.setData({
        loadinSure: 'woyilingqu', //redBtn
      });
    }
  },
  // ]]============================================公用=========
  // 发送fromID
  sendFormId: function(e) {
    var that = this;
    // 
    if (e.detail.formId == undefined || e.detail.formId == 'the formId is a mock one') {
      console.log('----------------------------------------');
      console.log(e.detail);
    } else {
      var openid = wx.getStorageSync("openid");
      that.setData({
        form_id: e.detail.formId,
      });
      if (app.globalData.openid.length > 0 && e.detail.formId) {
        net.requestHttp('bargain/index/addFormid', { form_id: e.detail.formId, user_id: app.globalData.user_id, openid: openid })
      }
    }
  },
  refrshImage: function() {
    var that = this;
    var timestamp = Date.parse(new Date());
    var openid = wx.getStorageSync("openid");

    that.setData({
      codeImage: app.globalData.service + 'bargain/index/verify?openid=' + openid + '&time=' + timestamp,
    })
  },
  // =规则页面进入
  turnToRule: function() {
    wx.navigateTo({
      url: '../webViewPage/webviewpage?state=1',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    if (e.from === 'button') {
      return {
        title: '老铁：帮我砍价，你也可以获得最高518元现金红包哦！',
        imageUrl: '../../image/bagarin.png',
        path: 'pages/Bargain/Bargain?help_id=' + app.globalData.user_id
      }
    } else {
      return {
        title: '邀请好友来砍价，超值代金券等你拿！',
        imageUrl: '',
        path: 'pages/Bargain/Bargain?'
      }
    }
  },
  //弹窗我知道了按钮事件
  _close_dialog: function() {
    this.BargainDialog = this.selectComponent("#BargainDialog");
    this.BargainDialog.hiddenDialog();
    var that = this;
    that.chongzhiyemian();
  },
  clearstroe: function() {
    for(var a=0;a<20;a++){
      wx.clearStorageSync();
    }
    wx.showToast({
      title: '缓存已清空',
    })
  },
  // 浮窗 跳转
  setTouchMove: function (e) {
  
    //此处clientY与clientX为拖动悬浮窗超过设定的大小会返回默认显示位置
    if (e.touches[0].clientX < 350 && e.touches[0].clientY < 550 && e.touches[0].clientX > 0 && e.touches[0].clientY > 0) {
      this.setData({
        left: e.touches[0].clientX,
        top: e.touches[0].clientY
      })
    } else {
      this.setData({
        left: 0, //默认显示位置 left距离
        top: 250  //默认显示位置 top距离
      })
    }
  },
  goHome: function () {
    wx.reLaunch({
      url: '../index/index?from=1',
    })
  },
  understandApp: function () {
    wx.navigateTo({
      url: '../webViewPage/Webview?url=http://e.yijiedai.com/about?platform=ios',
    })
  },
})